package cn.yunlang.zhangZhongFei.util.filter;

import cn.yunlang.zhangZhongFei.entity.SysUser;
import com.alibaba.fastjson2.JSON;
import cn.yunlang.zhangZhongFei.constant.AuthenticationConstants;
import cn.yunlang.zhangZhongFei.entity.LoginUser;
import cn.yunlang.zhangZhongFei.util.JwtUtil;
import cn.yunlang.zhangZhongFei.util.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;

import java.io.IOException;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token
        String userid;
        try {
            Claims claims = new JwtUtil().parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("" +
                    "token非法");
        }

        // 从redis中获取用户信息
//        String userToken = redisUtil.get(AuthenticationConstants.BACKSTAGE_USER_LOGIN_TOKEN + userid);
        String userToken = "";





            RedisClient redisClient = RedisClient.create("redis://localhost:6379");
            StatefulRedisConnection<String, String> connection = redisClient.connect();



            // 从Redis获取并反序列化
            RedisCommands<String, String> syncCommands = connection.sync();
            String retrievedJson = syncCommands.get(AuthenticationConstants.BACKSTAGE_USER_LOGIN_TOKEN + userid);




            try {
                ObjectMapper objectMapper = new ObjectMapper();
                SysUser sysUserRedis = objectMapper.readValue(retrievedJson, SysUser.class);
                userToken=sysUserRedis.getToken();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }





//        String userToken = token;
        if (Objects.isNull(userToken)) {
            throw new RuntimeException("用户未登录");
        }
        if (!Objects.equals(token, userToken)) {
            throw new RuntimeException("token异常");
        }


        // 存入SecurityContextHolder
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userid, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}
